#!/usr/bin/env python
# -*- coding: utf-8 -*-

from optparse import OptionParser
import os
import signal
import time

__version__ = '0.1'

#i = 0

def handler_request():
    """
    User function. Write your codes here.
    The return variable is important.

    @return: True, got data, want to iterate the next one immediately.
             False, no data found, let's sleep some time, then try again.
    """
#    global i
#    i += 1
#    print "OK", i
#    if i < 10:
#        return True
#    if i > 30:
#        i = 0
#    return False

    return False

def run(opts):
    """
    Want to change the sleep scheduling strategy, signal handle strategy?
    Rewrite here...
    """
    _max = 10
    _idle = _max 
    while True:
        while handler_request():
            _idle = 0
            if got_sigterm > 0:
                break
        if got_sigterm > 0:
            # quit...
            os._exit(0)

        _idle += 1
        if _idle > _max:
            _idle = _max
        _t = pow(float(_idle) / _max, 2)
        time.sleep(_t)

def daemon():
    try:
        pid = os.fork()
        if pid > 0:
            os._exit(0)
    except OSError, e:
        raise Exception, "%s [%d]" % (e.strerror, e.errno)

    os.setsid()

    try:
        pid = os.fork()
        if pid > 0:
            os._exit(0)
    except OSError, e:
        raise Exception, "%s [%d]" % (e.strerror, e.errno)

    os.chdir('/')
    os.umask(0)

    import resource
    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
    if (maxfd == resource.RLIM_INFINITY):
        maxfd = 1024
  
    # Iterate through and close all file descriptors.
    for fd in range(0, maxfd):
        try:
            os.close(fd)
        except OSError:
            pass

    os.open("/dev/null", os.O_RDWR)
    os.dup2(0, 1)
    os.dup2(0, 2)
    return 0


got_sigint = 0
got_sigterm = 0

def handle_sigint(signum, frame):
    global got_sigint
    got_sigint += 1
    raise KeyboardInterrupt

def handle_sigterm(signum, frame):
    global got_sigterm
    got_sigterm += 1


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-d", "--daemon", dest="daemon_mode",
                      action="store_true",
                      help="Run as daemon mode")
    parser.add_option("-e", "--err-log", dest="err_log",
                      help="Run as daemon mode")
    (options, args) = parser.parse_args()

    # signal handler
    signal.signal(signal.SIGTERM, handle_sigterm)
    signal.signal(signal.SIGINT, handle_sigint)

    # daemon ?
    if options.daemon_mode:
        print "Run as daemon..."
        daemon()

    # go
    run(options)

